package edu.task.controller;

import edu.task.common.base.BaseController;
import edu.task.common.result.RestResult;
import edu.task.model.SysTask;
import edu.task.model.vo.SysProjectVO;
import edu.task.model.vo.SysTaskVO;
import edu.task.service.SysProjectService;
import edu.task.service.SysTaskService;
import edu.task.utils.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 任务表控制层
 */
@RestController
@Log
@EnableScheduling
@RequestMapping("/system/task")
public class SysTaskController extends BaseController {

    @Autowired
    SysTaskService taskService;

    @Autowired
    SysProjectService projectService;

    /**
     * 显示任务表所有数据
     */
    @GetMapping("/list")
    public RestResult list() {
        RestResult ajax = RestResult.success();
        ajax.put(RestResult.DATA_TAG, taskService.selectTaskList());
        return ajax;
    }


    /**
     * 任务新增
     */
    @PostMapping
    public RestResult add(@RequestBody SysTaskVO task) {
        boolean flag = taskService.insertTask(task);
        return toAjax(flag ? 1 : 0);
    }

    /**
     * 删除任务
     */
    @DeleteMapping("/{taskId}")
    public RestResult remove(@PathVariable Long taskId){
        return toAjax(taskService.deleteTaskById(taskId));
    }

    /**
     * 修改新增
     */
    @PutMapping
    public RestResult edit(@Validated @RequestBody SysTaskVO task) {
        boolean flag = taskService.updateTask(task);
        return toAjax(flag ? 1 : 0);
    }

    /**
     * 根据任务编号获取任务列表信息
     */
    @GetMapping(value = {"/","/{taskId}"})
    public RestResult getInfo(@PathVariable(value = "taskId",required = false) List<Long> taskId){
        RestResult ajax = RestResult.success();
        if (StringUtils.isNotNull(taskId)){
            ajax.put(RestResult.DATA_TAG, taskService.selectTaskById(taskId));
            ajax.put("projectIds", projectService.selectProjectByTaskId(taskId));
        }
        return ajax;
    }

    /**
     * 根据任务编号数组获取任务列表信息
     */
    @GetMapping("/taskList")
    public RestResult taskList(@RequestBody SysTaskVO taskIds){
        RestResult ajax = RestResult.success();
        List<Long> task = Arrays.asList(taskIds.getTaskIds());
        if (StringUtils.isNotNull(task)){
            ajax.put(RestResult.DATA_TAG, taskService.selectTaskByTaskId(task));
        }
        return ajax;
    }

    /**
     * 每5秒更新任务剩余时间
     */
    @Scheduled(cron = "*/5 * * * * ?")
    @SneakyThrows
    public void inset() {
//        log.info("---------定时任务开始执行---------" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
        List<SysTask> sysTasks = taskService.selectTaskListByStatus();
        for (int i=0;i< sysTasks.size();i++){
            if (!sysTasks.get(i).getSurplus().equals("00:00:00")) {
                Date date = new Date();
                // 时间对比
//                int compare = sysTasks.get(i).getEstimatedTime().compareTo(date);
                long Time = sysTasks.get(i).getEstimatedTime().getTime()-date.getTime();
                sysTasks.get(i).setSurplus(taskService.getTimeString(Time));
                if (Time > 0) {
                    if (sysTasks.get(i).getSurplus().compareTo("00:00:05")>=0){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date d = sdf.parse("2008-08-08 00:00:00");
                        String[] str = sysTasks.get(i).getSurplus().split(":");
                        int[] array = Arrays.asList(str).stream().mapToInt(Integer::parseInt).toArray();
                        long time = d.getTime();
                        for (int t=0;t<array.length;t++){
                            if (t==0){
                                time = time + array[t]*1000*60*60;
                            } else if (t==1) {
                                time = time + array[t]*1000*60;
                            } else if (t==2) {
                                time = time + array[t]*1000;
                            }
                        }
                        time = time - 5000;
                        date.setTime(time);
                        String shu = date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
                        String[] shu2 = shu.split(":");
                        String newShu="";
                        for (int j=0;j<shu2.length;j++) {
                            if (shu2[j].length()<2) {
                                shu2[j] = "0"+ shu2[j];
                            }
                            if (j != shu2.length-1) {
                                newShu = newShu + shu2[j] + ":";
                            }else {
                                newShu = newShu + shu2[j];
                            }
                        }
                        sysTasks.get(i).setSurplus(newShu);
                        taskService.updateTasks(sysTasks.get(i));
                    }else {
                        sysTasks.get(i).setSurplus("00:00:00");
                        taskService.updateTasks(sysTasks.get(i));
                    }
                } else {
                    sysTasks.get(i).setSurplus("00:00:00");
                    taskService.updateTasks(sysTasks.get(i));
                }
            }
        }

//        log.info("---------定时任务执行成功---------" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
    }

}
